package com.example.tuike.service;

import com.example.tuike.common.SubscriptionStatus;
import com.example.tuike.entity.Subscription;
import com.example.tuike.entity.User;
import com.example.tuike.exception.BusinessException;
import com.example.tuike.exception.ResourceNotFoundException;
import com.example.tuike.mapper.FeedsMapper;
import com.example.tuike.mapper.PlatformsMapper;
import com.example.tuike.mapper.SubscriptionMapper;
import com.example.tuike.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/*** @Author supersaiya
 * @Description TODO

 * @Date 2025/1/29 20:07

 * @Version 1.0*/
@Service
@RequiredArgsConstructor
public class SubscriptionService {
    private final SubscriptionMapper subscriptionMapper;
    private final UserMapper userMapper;
    private final FeedsMapper feedsMapper;

    // 创建订阅（带校验）
    @Transactional
    public Subscription createSubscription(Subscription subscription) {
        // 校验用户和平台存在性
        if (userMapper.findById(subscription.getUserId()) == null) {
            throw new ResourceNotFoundException("用户不存在");
        }
        if (feedsMapper.findById(subscription.getFeedId()) == null) {
            throw new ResourceNotFoundException("订阅源不存在");
        }
        if(subscriptionMapper.findByUserIdAndStatus(subscription.getUserId(),SubscriptionStatus.ACTIVE)!=null){
            throw new IllegalStateException("用户已经有一个活跃的订阅源.");
        }

        // 设置默认时间和状态（如果未设置）
        if (subscription.getStatus() == null) {
            subscription.setStatus(SubscriptionStatus.ACTIVE);
        }
        subscription.setCreatedAt(LocalDateTime.now());
        subscription.setUpdatedAt(LocalDateTime.now());

        subscriptionMapper.insert(subscription);
        return subscription;
    }

    // 更新订阅配置
    @Transactional
    public Subscription updateSubscription(Integer subscriptionId, Subscription subscription) {
        Subscription existing = subscriptionMapper.findById(subscriptionId);
        if (existing == null || existing.getStatus() == SubscriptionStatus.INACTIVE) {
            throw new BusinessException("订阅不存在或已取消");
        }

        // 只允许更新状态
        existing.setStatus(subscription.getStatus());
        existing.setUpdatedAt(LocalDateTime.now());

        subscriptionMapper.update(existing);
        return existing;
    }

    // 获取用户订阅列表（按状态过滤）
    public List<Subscription> getUserSubscriptions(Integer userId, SubscriptionStatus status) {
        return subscriptionMapper.findByUserIdAndStatus(userId, status);
    }

    @Transactional
    public Subscription toggleSubscription(Integer userId, Integer feedId, String status, String title) {
        // 校验用户和订阅源存在性
        if (userMapper.findById(userId) == null) {
            throw new ResourceNotFoundException("用户不存在");
        }
        if (feedsMapper.findById(feedId) == null) {
            throw new ResourceNotFoundException("订阅源不存在");
        }


        // 查询是否已有订阅记录
        Subscription existing = subscriptionMapper.findByUserIdAndFeedId(userId, feedId);
        if (existing == null) {
            // 如果没有订阅记录，创建新的订阅
            Subscription newSubscription = new Subscription();
            newSubscription.setUserId(userId);
            newSubscription.setFeedId(feedId);
            newSubscription.setStatus(SubscriptionStatus.valueOf(status));
            newSubscription.setTitle(title); // 设置标题字段
            newSubscription.setCreatedAt(LocalDateTime.now());
            newSubscription.setUpdatedAt(LocalDateTime.now());
            subscriptionMapper.insert(newSubscription);
            return newSubscription;
        } else {
            // 如果已有订阅记录，更新订阅状态和标题
            existing.setStatus(SubscriptionStatus.valueOf(status));
            existing.setTitle(title); // 更新标题字段
            existing.setUpdatedAt(LocalDateTime.now());
            subscriptionMapper.update(existing);
            return existing;
        }
    }
    public boolean isSubscribed(Integer userId, Integer feedId) {
        return subscriptionMapper.isSubscribed(userId, feedId);
    }
}
